package com.bwie.list.controller;

import com.bwie.common.domain.Data1;
import com.bwie.common.domain.Data2;
import com.bwie.common.domain.Data3;
import com.bwie.common.utils.StringUtils;
import com.bwie.list.mapper.TestMapper;
import com.bwie.list.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
public class TestController {
    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private TestService service;
    @Autowired
    private TestMapper testMapper;

    private static final String[] NAMES={"zhangsan", "lisi", "wangwu", "zhaoliu", "tianqi"};

    private static final String[] CAR_PREFIXES={"京", "沪", "津", "渝", "冀", "晋", "蒙", "辽", "吉", "黑","藏", "陕", "甘", "青", "宁", "新"};

    private static final String CAR_LETTERS="ABCDEFGHJKLMNPQRSTUVWXYZ";
    private static final String CAR_NUMBERS="0123456789";


    @Scheduled(cron = "0 5 * * * ?")
    @Transactional
    public void producer(){
        Random random = new Random();

        //8位数随机数
        String id = String.format("%08d", random.nextInt(99999999));

        //随机名字
        String name= NAMES[random.nextInt(NAMES.length)];

        //随机6位数
        String card = String.format("%06d", random.nextInt(999999) + 1);

        //年龄
        int age = 10+random.nextInt(90);

        // 车牌格式：省份简称 + 字母 + 5位数字/字母
        StringBuilder sb = new StringBuilder();
        sb.append(CAR_PREFIXES[random.nextInt(CAR_PREFIXES.length)]);
        sb.append(CAR_LETTERS.charAt(random.nextInt(CAR_LETTERS.length())));
        for (int i = 0; i < 5; i++) {
            // 随机选择字母或数字
            int randCharType = random.nextInt(2);
            if (randCharType == 0) {
                sb.append(CAR_LETTERS.charAt(random.nextInt(CAR_LETTERS.length())));
            } else {
                sb.append(CAR_NUMBERS.charAt(random.nextInt(CAR_NUMBERS.length())));
            }
        }
        String plate = sb.toString();

        //身份证
        StringBuilder sb1 = new StringBuilder();
        // 地区码
        sb.append(String.format("%06d", random.nextInt(999999)));
        // 出生日期码，这里简单随机生成
        sb.append(String.format("%08d", random.nextInt(99999999)));
        // 顺序码
        sb.append(String.format("%03d", random.nextInt(999)));
        // 校验码通常需要一个更复杂的算法来生成，这里简单用一个随机数字代替
        sb.append(CAR_NUMBERS.charAt(random.nextInt(CAR_NUMBERS.length())));
        String id_card = sb1.toString();

        String photo1="";
        String photo2="";

        //生成时间
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formattedDate = sdf.format(date);

        Data1 data1 = new Data1();
        data1.setId(id);
        data1.setXm(name);
        data1.setCard(card);
        data1.setAge(age);
        data1.setTime(formattedDate);
        kafkaTemplate.send("topic1", UUID.randomUUID().toString().replaceAll("_",""),data1);

        Data2 data2 = new Data2();
        data2.setId(id);
        data2.setXm(name);
        data2.setIdCard(id_card);
        data2.setPhoto1(photo1);
        data2.setPhoto2(photo2);
        kafkaTemplate.send("topic2",UUID.randomUUID().toString().replaceAll("_",""),data2);

        Data3 data3 = new Data3();
        data3.setId(id);
        data3.setPlate(plate);
        data3.setTime(formattedDate);
        kafkaTemplate.send("topic3",UUID.randomUUID().toString().replaceAll("_",""),data3);

    }

    @Scheduled(cron = "0 0/1 * * * ?")
    public void test() {
        String dataEndTime = (String) redisTemplate.opsForValue().get("dataEndTime");
        if (StringUtils.isEmpty(dataEndTime)) {
            List<Data1> data1All = service.findData1All();
            for (Data1 data1 : data1All) {
                Data2 data2ById = testMapper.findData2ById(data1.getId());
                Data3 data3ById = testMapper.findData3ById(data1.getId());

                if (data2ById == null || data3ById == null) {
                    return;
                }

                String substring1 = data2ById.getPhoto1().substring(data2ById.getPhoto1().indexOf(",") + 1);
                String substring2 = data2ById.getPhoto2().substring(data2ById.getPhoto2().indexOf(",") + 1);


                String savedImageName1 = null;
                String savedImageName2 = null;

                try {
                    savedImageName1 = saveBase64Image(substring1, "D:\\text01");
                    savedImageName2 = saveBase64Image(substring2, "D:\\text01");
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

                // 指定文件所在的目录
                String directoryPath = "D:\\text01/";
                String randomFileName = generateRandomFileName(".txt");
                String filePath = directoryPath + randomFileName;


                try {
                    String str = "\t" + data1.getId() + "\t"
                            + data1.getXm() + "\t"
                            + data1.getCard() + "\t"
                            + data1.getAge() + "\t"
                            + data1.getTime() + "\t"
                            + data2ById.getXm() + "\t"
                            + data2ById.getIdCard() +
                            "\t" + savedImageName1 + "\t"
                            + savedImageName2 + "\t" +
                            data3ById.getPlate() + "\t" + data3ById.getTime();
                    BufferedWriter writer = new BufferedWriter(new FileWriter(filePath));
                    writer.write(str);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            Data1 data1 = data1All.get(0);

            redisTemplate.opsForValue().set("dataEndTime", data1.getTime(), 30, TimeUnit.MINUTES);
        }


    }

    /**
     * 随机文件名
     * @param s
     * @return
     */
    private String generateRandomFileName(String s) {
        Random random = new Random();
        //随机前缀
        String prefix = String.format("%08d", random.nextInt(99999999));
        return  prefix+s;

    }

    /**
     * 解析base64
     * @param base64ImageStr
     * @param targetDir
     * @return
     * @throws IOException
     */
    public static String saveBase64Image(String base64ImageStr, String targetDir) throws IOException {

        byte[] imageBytes = Base64.getDecoder().decode(base64ImageStr);
        String extension = "jpg";
        String fileName = UUID.randomUUID().toString() + "." + extension;
        // 指定保存路径
        Path path = Paths.get(targetDir, fileName);

        // 将字节数据写入文件
        try (FileOutputStream fos = new FileOutputStream(path.toFile())) {
            fos.write(imageBytes);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return fileName;
    }


}
